<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Contacts;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\Event;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\FormField;
use addons\qingdongams\model\Leads as LeadsModel;
use addons\qingdongams\model\LeadsFile;
use addons\qingdongams\model\LeadsOther;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\Record;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Remind;
use think\Db;
use think\Exception;
/**
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
/**
 * 线索接口
 */
class Leads extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//添加线索
	public function addLeads() {
		$params = $this->request->post();
		if (empty($params['leads'])) {
			$this->error('线索信息不能为空');
		}
		// 表单验证
		if (($result = $this->qingdongamsValidate($params['leads'],get_class(), 'create')) !== true) {
			$this->error($result);
		}

        $result = FormField::checkFields(FormField::LEADS_TYPE,$params['leads']);
        if ($result !== true) {
            $this->error($result);
        }
		try {
			$leadsId                     = LeadsModel::createLeads($params['leads']);

		} catch (Exception $e) {
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('添加线索成功');
		}
	}


	//获取线索列表
	public function getList() {
		$name   = input('name', '');
		$mobile = input('mobile', '');
		$limit  = input("limit/d", 10);
		$params = $this->request->post();

        $where= FormField::updateWhereField(FormField::LEADS_TYPE,$params);

        if (isset($params['createtime']) && $params['createtime']) {//跟进状态
			$createtime          = $params['createtime'];
			$where['createtime'] = ['between', setTimes($createtime,'time')];
		}


        //0:全部 1：我负责的 2：下属负责的 3：今日待跟进 4:今日已跟进 5:从未跟进的
        $type = input('type',0);
        switch($type){
            case 1:
                $staff = Staff::info();
                $where['owner_staff_id'] =  $staff->id;
                break;
            case 2:
                $where['owner_staff_id'] =  array('in',Staff::getLowerStaffId());
                break;
            case 3:
                $start = date('Y-m-d 00:00:00');
                $end = date('Y-m-d 23:59:59');
                $record = collection(Record::where(array('status'=>0,'relation_type'=>4,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
                $relationId = [];
                foreach($record as $k=>$v){
                    $relationId[] = $v['relation_id'];
                }
                $where['id'] =  array('in',$relationId);
                $staff = Staff::info();
                $where['owner_staff_id'] =  $staff->id;
                break;
            case 4:
                $start = date('Y-m-d 00:00:00');
                $end = date('Y-m-d 23:59:59');
                $relationId = Record::where(array('status'=>1,'relation_type'=>4,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->column('relation_id');
                $where['id'] =  array('in',$relationId);
                $staff = Staff::info();
                $where['owner_staff_id'] =  $staff->id;
                break;
            case 5:
                $record = collection(Record::where(array('relation_type'=>4))->column('relation_id'))->toArray();
                $where['id'] =  array('not in',$record);
                $staff = Staff::info();
                $where['owner_staff_id'] =  $staff->id;
                break;
            default:
                $where['owner_staff_id'] =  array('in',Staff::getMyStaffIds());
                break;

        }
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['owner_staff_id'] = $params['staff_id'];
        }
        if ($name) {
			$where['name'] = ['like', "%{$name}%"];
		}
		if ($mobile) {
			$where['mobile'] = ['like', "%{$mobile}%"];
		}
        $where['is_transform'] = 0;
		$records           = LeadsModel::where($where)->with(['ownerStaff'])->field('id,owner_staff_id,name,follow,mobile,level,next_time,source')->order('id desc')->paginate($limit);
		$this->success('请求成功', $records);
	}


	//获取线索详情
    public function getDetail()
    {
        $id = input('id', '', 'intval');
        $leads = LeadsModel::where(['id' => $id])->with([
            'createStaff',
            'ownerStaff'
        ])->find();
        if (empty($leads)) {
            $this->error('信息不存在');
        }
        $leads = $leads->toArray();
        $leads = LeadsOther::getOther($leads);

        $this->success('请求成功', $leads);
    }


	//获取选择列表
	public function getSelectList() {
		$where   = ['owner_staff_id' => $this->auth->id];
        $where['is_transform'] = 0;
		$records = LeadsModel::where($where)->field('id,owner_staff_id,name,follow,mobile')->order('id desc')->select();
		$this->success('请求成功', $records);
	}

    //转移线索
    public function transfer()
    {
        $id = input('id');
        $staff_id = input('staff_id');
        if (!$staff_id || !$id) {
            $this->error('参数错误');
        }
        $staff = Staff::get($staff_id);
        if (empty($staff)) {
            $this->error('接收对象不存在');
        }
        $row = LeadsModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('线索不存在');
        }
        try {
            LeadsModel::transfer($id, $staff_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('转移线索成功');
    }

	//修改线索
	public function editLeads() {
		$id     = input('id');
		$params = $this->request->post();
		$row    = LeadsModel::where(['id' => $id])->find();
		if (empty($row)) {
			$this->error('线索信息不存在');
		}
		// 表单验证
		if (($result = $this->qingdongamsValidate($params,get_class(), 'create')) !== true) {
			$this->error($result);
		}

        $result = FormField::checkFields(FormField::LEADS_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
		try {
			LeadsModel::updateLeads($params);
		} catch (Exception $e) {
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('修改线索成功');
		}
	}


	//删除线索
	public function delLeads() {
		$id    = input('id');
		$model = new LeadsModel();
		$row   = $model->where(['owner_staff_id' => $this->auth->id, 'id' => $id])->find();
		if (empty($row)) {
			$this->error('不是线索归属人，无法删除数据！');
		}
		if ($model->where(['id' => $id])->delete()) {
			$this->success('删除成功');
		}
		$this->error('删除失败');
	}


	//获取附件列表
	public function getFilesList() {
		$id = input('leads_id');

		$files = LeadsFile::where(['leads_id' => $id])->field('file_id')->with(['file'])->select();
		$this->success('请求成功', $files);
	}
    //移入线索池
    public function movePool()
    {
        $id = input('id');
        $row = LeadsModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('线索不存在');
        }
        Db::startTrans();
        try {
            LeadsModel::movePool($id);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('放入成功');
    }
    /**
     * 转为客户
     */
    public function convert_customer()
    {
        $id    = input('id');
        $row = LeadsModel::get($id);
        if (empty($row)) {
            $this->error('线索不存在');
        }
        $form=Form::getDataValue(Form::LEADS_TYPE);
        $fields=[];
        foreach ($form as $v){
            if(isset($v['matching']) && $v['matching']){
                $fields[$v['matching']]=$v['id'];
            }
        }
        Db::startTrans();
        try {
            $customer=[
                'name'=>$row['name'],
                'mobile' => $row['mobile'],
                'leads_id' => $row['id'],
                'create_staff_id' => $row['owner_staff_id'],
                'owner_staff_id' => $row['owner_staff_id'],
            ];
            foreach ($fields as $k => $f) {
                $customer[$k] = $row[$f] ?? '';
            }

            //线索转化
            $leads_id = '';
            if (isset($customer['leads_id'])) {
                $leads_id = $customer['leads_id'];
            }
            $customer_id = Customer::createCustomer($customer, $leads_id);
            $contracts = [
                'customer_id' => $customer_id,
                'is_major' => 1,
                'name' => $row['name'],
                'mobile' => $row['mobile'],
                'remarks' => $row['remarks'],
                'create_staff_id' => $row['owner_staff_id'],
                'owner_staff_id' => $row['owner_staff_id'],
            ];
            Contacts::createContacts($contracts);
            $staff                     = Staff::info();
            $remind = Remind::where(['type'=>'leads_tranfer'])->find();
            if($remind && $remind['staff_ids']){
                $remind_staff = explode(',',$remind['staff_ids']);
                foreach($remind_staff as $kr=>$vr){
                    Message::addMessage(Message::LEADS_TRANFER,$id,$vr,$staff->id);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('转客成功');
    }

}
